clear all
*cap log close
set more off
set seed 603


// Construct wide data --------------------------------------------------------------------
use "${data}/out/4-main", clear
keep citationid offensedate dlnumber
joinby dlnumber using "${data}/out/1-offending"

* pre-period indicators -----
gen pre_q1 = (offensedate - date > 1)   & (offensedate - date <= 90)
gen pre_q2 = (offensedate - date > 90)  & (offensedate - date <= 180)
gen pre_q3 = (offensedate - date > 180) & (offensedate - date <= 270)
gen pre_q4 = (offensedate - date > 180) & (offensedate - date <= 360)
gen pre_q5 = (offensedate - date > 360) & (offensedate - date <= 450)
gen pre_q6 = (offensedate - date > 450) & (offensedate - date <= 540)
gen pre_q7 = (offensedate - date > 540) & (offensedate - date <= 630)
gen pre_q8 = (offensedate - date > 630) & (offensedate - date <= 720)

* post-period indicators --------
gen post_q1 = (date - offensedate > 1)   & (date - offensedate <= 90)
gen post_q2 = (date - offensedate > 90)  & (date - offensedate <= 180)
gen post_q3 = (date - offensedate > 180) & (date - offensedate <= 270)
gen post_q4 = (date - offensedate > 180) & (date - offensedate <= 360)
gen post_q5 = (date - offensedate > 360) & (date - offensedate <= 450)
gen post_q6 = (date - offensedate > 450) & (date - offensedate <= 540)
gen post_q7 = (date - offensedate > 540) & (date - offensedate <= 630)
gen post_q8 = (date - offensedate > 630) & (date - offensedate <= 720)

* code events of interest --------------
gen cite  = (citation==1)
gen speed = (viol == 575)
gen other = (citation==1) & (viol!=575)
*gen crash = (crash == 1)
*gen omove = (viol_class=="M") & (viol != 575)
gen amove = (viol_class=="M")
gen nmove = (viol_class!="M")

* ALL INDICATORS *
foreach x in cite speed other crash amove nmove {
	foreach t of varlist pre_q1 - post_q8 {
		gen `x'_`t' = `x'*`t'
	}	
}

collapse (max) *_pre_* *_post_*, by(citationid) fast
qui compress
saveold "${temp}/wide_data", replace
// ---------------------------------------------------------------------------------------


// Dynamic plot for main text -----------------------------------------------------------
// store overall est for printing ---------------------------
use "${data}/out/4-main", clear
gen Y = cite_ny1

reghdfe Y Z, absorb(totfe) vce(cluster officerid)
local bprint = "{it:{&beta}{subscript:RF}} = `:di %5.4f _b[Z]' (`:di %5.4f _se[Z]')"
qui summ Y if lenient == 1 
local mprint = "{it:{&mu}} = `:di %5.4f `r(mean)''"

// setup data. --------------------------------
keep citationid Z officerid totfe
merge 1:1 citationid using "${temp}/wide_data", keep(1 3) nogen
foreach x of varlist *_pre_* *_post_* {
	qui replace `x' = 0 if mi(`x')
}


// Estimate quarterly RF coefficients ------
gen tau = _n - 9 if _n<=17
foreach y in cite {

	gen b_`y'  = 0 if _n <= 17
	gen s_`y'  = 0 if _n <= 17
	gen lb_`y' = 0 if _n <= 17
	gen ub_`y' = 0 if _n <= 17


	forval t = 1/8 {
	
		reghdfe `y'_pre_q`t' Z, absorb(totfe) vce(cluster officerid)
		replace b_`y'  = _b[Z] if tau == -`t'
		replace s_`y'  = _se[Z] if tau == -`t'
		replace lb_`y' = _b[Z] - 1.96*_se[Z] if tau == -`t'
		replace ub_`y' = _b[Z] + 1.96*_se[Z] if tau == -`t'
	
		reghdfe `y'_post_q`t' Z, absorb(totfe) vce(cluster officerid)
		replace b_`y'  = _b[Z] if tau == `t'
		replace s_`y'  = _se[Z] if tau == `t'
		replace lb_`y' = _b[Z] - 1.96*_se[Z] if tau == `t'
		replace ub_`y' = _b[Z] + 1.96*_se[Z] if tau == `t'
	
	}
}


// Build plot -------------------
#delimit ;
twoway rarea ub_cite lb_cite tau, fcolor(navy%15) lwidth(none) lcolor(navy) ||
line b_cite tau, lcolor(navy) lwidth(medthick) lpattern(solid)
graphregion(color(white)) plotregion(lcolor(black) lwidth(medthin))
ylab(-0.015(0.005)0.015,nogrid) xlabel(-8(4)8, nogrid)
xtitle("Quarter Around FHP Citation") ytitle("Stringency Effect")
yline(0,lpattern(dash) lcolor(cranberry) lwidth(vthin)) 
xline(0,lpattern(dash) lcolor(cranberry) lwidth(vthin))
legend(ring(0) pos(2) order(2 1) cols(1) region(lstyle(border))
lab(2 "RF Estimate") lab(1 "95% CI"))
text(-0.009 -4.5 "1-year effect:" "`bprint'" "`mprint'", place(s) size(med)) ;
#delimit cr
graph export "${out}/main/reduced_form.pdf", replace
// ------------------------------------------------------------------------------------------



// Dynamic plot for appendix (multiple outcomes) --------------------------------------------
use "${data}/out/4-main", clear
keep citationid officerid Z totfe
merge 1:1 citationid using "${temp}/wide_data", keep(1 3) nogen
foreach x of varlist *_pre_* *_post_* {
	qui replace `x' = 0 if mi(`x')
}

/// Estimate quarterly RF coefficients --------
gen tau = _n - 9 if _n<=17
foreach y in cite speed crash {

	gen b_`y'  = 0 if _n <= 17
	gen lb_`y' = 0 if _n <= 17
	gen ub_`y' = 0 if _n <= 17

	forval t = 1/8 {
	
		reghdfe `y'_pre_q`t' Z, absorb(totfe) vce(cluster officerid)
		replace b_`y'  = _b[Z] if tau == -`t'
		replace lb_`y' = _b[Z] - 1.96*_se[Z] if tau == -`t'
		replace ub_`y' = _b[Z] + 1.96*_se[Z] if tau == -`t'
	
		reghdfe `y'_post_q`t' Z, absorb(totfe) vce(cluster officerid)
		replace b_`y'  = _b[Z] if tau == `t'
		replace lb_`y' = _b[Z] - 1.96*_se[Z] if tau == `t'
		replace ub_`y' = _b[Z] + 1.96*_se[Z] if tau == `t'
	
	}
}


#delimit ; 
twoway 
rarea ub_cite  lb_cite  tau, fcolor(dknavy%15)  lwidth(none) ||
rarea ub_speed lb_speed tau, fcolor(dkgreen%15) lwidth(none) ||
rarea ub_crash lb_crash tau, fcolor(purple%15)  lwidth(none) ||
connected b_cite  tau, msymbol(O) mcolor(dknavy) msize(small) lcolor(dknavy) ||
connected b_speed tau, msymbol(D) mcolor(dkgreen) msize(small) lcolor(dkgreen) ||
connected b_crash tau, msymbol(X) mcolor(purple) lcolor(purple) msize(medlarge)
graphregion(color(white)) plotregion(lcolor(black) lwidth(medthin))
ylab(-0.015(0.005)0.015,nogrid) xlab(-8(4)8,nogrid)
yline(0,lpattern(dash) lcolor(cranberry)) xline(0,lpattern(dash) lcolor(cranberry))
xtitle("Quarter Around FHP Citation") ytitle("Reduced Form Estimate")
legend(ring(0) pos(2) order(4 5 6) region(lstyle(border))
lab(4 "Any Violation") lab(5 "Speeding Violation") lab(6 "Crash") cols(1)) ;
#delimit cr
graph export "${out}/apx_deter/rf_dynamic.pdf", replace
// ------------------------------------------------------------------------------------------

* delete wide data 
rm "${temp}/wide_data.dta"
* -------------------------------------------------------------------------------------------------------------



* reduced form scatter plots ----------------------------------------------------------------------------------

* names for output plots ----------
local name1 = "cite"
local name2 = "speed"
local name3 = "crash"
local name4 = "contest"

* looping over outcomes --------------
local k = 1
foreach Y in cite_ny1 speed_ny1 crashany_ny1 contest {

	// prep data ------------------
	use "${data}/out/4-main", clear
	gen Y = `Y'

	// store coefficient ----------
	reghdfe Y Z, absorb(totfe) vce(cluster officerid)
	local B = _b[Z]
	local b = "{it:{&beta}{subscript:RF}} = `:di %5.4f _b[Z]' (`:di %5.4f _se[Z]')"

	// store control mean ---------
	summ Y if lenient == 1
	local m = "{it:{&mu}} = `:di %4.3f r(mean)'"

	// residualize -----------------
	reghdfe Y, absorb(totfe) nocons resid
	predict rY, resid
	reghdfe Z, absorb(totfe) nocons resid
	predict rZ, resid

	// Manual binscatter -----------
	binscatter rY rZ, nq(20) nodraw gen(BIN)
	gen xBIN = _n if _n <= 20
	gen mZ = .
	gen mY = .
	forval i = 1/20 {
		qui summ rZ if BIN == `i'
		qui replace mZ = r(mean) if xBIN == `i'
		qui summ rY if BIN == `i'
		qui replace mY = r(mean) if xBIN == `i'
	}

	// nonparametric fit -----------
	_pctile rZ, n(100)
	scalar loZ = r(r2)
	scalar hiZ = r(r98)
	lpoly rY rZ if rZ>loZ & rZ<hiZ, nogr ci gen(x y) se(yse) degree(0) bw(0.2) kernel(tri)
	cap g ylb = y - 1.96*yse
	cap g yub = y + 1.96*yse

	// graphing parameters -----------
	// setup locations on graph
	if `B' > 0 {
		local legpos = 5
		local textx  = -0.25
	}
	if `B' <0 {
		local legpos = 7
		local textx  = 0.25
	}

	local upper = 0.015 
	local texty = 0.0145 
	local step  = 0.005

	if "`Y'" == "crashany_ny1" {
		local upper = 0.004 
		local texty = 0.0035
		local step  = 0.002
	}

	if "`Y'" == "contest" {
		local upper = 0.075
		local texty = 0.07
		local step  = 0.025
	}

	// build graph -----------
	#delimit ;
	twoway rarea yub ylb x, fintensity(15) fcolor(emidblue) lwidth(none) ||
	line y x, lwidth(medthick) lcolor(forest_green) ||
	scatter mY mZ, msize(medlarge) msymbol(Oh) mcolor(dknavy) ||
	lfit mY mZ, lwidth(medthick) lcolor(forest_green) lpattern(dash) 
	graphregion(color(white)) plotregion(lcolor(black) lwidth(medthin))
	ylab(-`upper'(`step')`upper',nogrid) xlab(-0.5(0.25)0.5,nogrid)
	xtitle("Officer Stringency")
	legend(ring(0) pos(`legpos') order(3 4 2 1) cols(2) region(lstyle(border))
	lab(3 "Local Mean") lab(4 "Linear Fit") lab(2 "Nonparametric Fit") lab(1 "95% CI"))
	text(`texty' `textx' "`b'" "`m'", place(s) size(medlarge)) ;
	#delimit cr
	graph export "${out}/apx_deter/rf_`name`k''.pdf", replace  
	local ++k

}
* -------------------------------------------------------------------------------------------------------------







